package bma.common.langutil.core;

import java.io.File;

import junit.framework.TestCase;
import bma.common.langutil.io.IOUtil;
import bma.common.langutil.log.filelog.AsyncFileLog;
import bma.common.langutil.log.filelog.CommonFileLogTask;
import bma.common.langutil.log.filelog.LogWriterRealm;
import bma.common.langutil.log.filelog.FileLogTask;
import bma.common.langutil.log.filelog.PerformanceFileLogTask;

public class AsynFileLogTC extends TestCase {

	final org.slf4j.Logger log = org.slf4j.LoggerFactory
			.getLogger(AsynFileLogTC.class);

	AsyncFileLog flog;

	@Override
	protected void setUp() throws Exception {
		super.setUp();

		File file = IOUtil.getUserDirFile("tmp");
		if (!file.exists()) {
			file.mkdir();
		}

		flog = new AsyncFileLog();
		flog.setLogDirFile(file);
		flog.start();
	}

	@Override
	protected void tearDown() throws Exception {
		flog.stop();
		super.tearDown();
	}

	public void testBase() throws Exception {

		for (int i = 0; i < 10; i++) {
			final String msg = "message " + i + "\n";
			flog.write(new FileLogTask() {

				@Override
				public void run(LogWriterRealm realm) {
					realm.write("test", msg);
				}
			});
			ObjectUtil.waitFor(this, 1000);
		}
	}

	public void testCommon() throws Exception {

		for (int i = 0; i < 10; i++) {
			CommonFileLogTask msg = new CommonFileLogTask("test");
			msg.addNow().addMessage("msg", "no." + i);
			flog.write(msg);
		}
		ObjectUtil.waitFor(this, 1000);
	}

	public void testCloseFlush() throws Exception {

		for (int i = 0; i < 10; i++) {
			final String msg = "message " + i + "\n";
			flog.write(new FileLogTask() {

				@Override
				public void run(LogWriterRealm realm) {
					realm.write("test", msg);
				}
			});
		}
	}

	public void testTimeFlush() throws Exception {
		flog.write(new FileLogTask() {

			@Override
			public void run(LogWriterRealm realm) {
				realm.write("test", "my message\n");
			}
		});
		ObjectUtil.waitFor(this, 6 * 1000);
	}
	
	public void testTimeRoll() throws Exception {
		flog.write(new FileLogTask() {

			@Override
			public void run(LogWriterRealm realm) {
				realm.write("test", "my message\n");
			}
		});
		ObjectUtil.waitFor(this, 2 * 1000);
		
		flog.write(new FileLogTask() {

			@Override
			public void run(LogWriterRealm realm) {
				realm.write("test", "my message2\n");
			}
		});
		ObjectUtil.waitFor(this, 2 * 1000);
	}

	public void testPerformance() throws Exception {

		PerformanceFileLogTask task = new PerformanceFileLogTask("test");
		task.addNow();
		task.begin();
		ObjectUtil.waitFor(this, 1100);
		flog.write(task.end());		
	}

	
}
